const OFFSET = 200;
const DURATION = 500;

const map = new WeakMap()
// 监听
const ob = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            // 播放动画
            const animation = map.get(entry.target)
            if (animation) {
                animation.play()
            }
        }
    })
})

function belowViewport(el) {
    // 判断元素是否在视图中
    const rect = el.getBoundingClientRect()
    return rect.top > window.innerHeight
}
export default {
    mounted(el) {
        if (!belowViewport(el)) {
            // 如果元素不在视图中，则不执行动画
            return
        }
        // 实现上滑动画
        // 关键帧：@keyframes
        // 动画配置：animation
        const animation = el.animate([{
            transform: `translateY(${OFFSET}px)`,
            opacity: 0
        }, {
            transform: `translateY(0px)`,
            opacity: 1
        }], {
            duration: DURATION,
            easing: 'ease-out',
            fill: 'forwards'
        })
        animation.pause();// 暂停动画
        ob.observe(el);// 监听元素
        map.set(el, animation)
    },
    unmounted(el) {
        // 取消监听
        ob.unobserve(el)
    }
}